package sfs

import (
	"context"
	"github.com/chicken-team-outside/chicken_transmission/api_messages"
	"github.com/golang/protobuf/proto"
	"go.uber.org/zap"
	"os"
)

func (p *FsClient) listDirProvider(ctx context.Context, header *api_messages.MessageHeader, data []byte) {
	if ctx.Err() != nil {
		return
	}
	query := new(api_messages.ListFilesQuery)
	err := proto.Unmarshal(data, query)
	var files []os.FileInfo
	if err != nil {
		zap.L().Warn("failed to unmarshal list dir query", zap.Any("header", header), zap.Error(err))
	} else {
		local := p.GetLocal()
		if local == nil {
			err = ErrNotSetLocalDriver
		} else {
			files, err = local.ListFiles(query.Path)
		}
	}
	result := new(api_messages.ListDirResponse)
	result.Status = encodeStatusMessage(err)
	if err == nil {
		result.Result = make([]*api_messages.FileInfo, 0)
		for _, info := range files {
			if query.Folder {
				if info.IsDir() {
					result.Result = append(result.Result, osFileInfoToApiMessage(info))
				}
			} else {
				result.Result = append(result.Result, osFileInfoToApiMessage(info))
			}
		}
	}
	err = p.sendReplyByHeader(ctx, header, result)
	if err != nil {
		zap.L().Warn("failed to send list dir response", zap.Any("header", header), zap.Error(err))
	} else {
		zap.L().Debug("send list dir response", zap.Any("header", header), zap.Any("result", result))
	}
}

func (p *FsClient) ListDir(ctx context.Context, clientId uint64, query *api_messages.ListFilesQuery) ([]FileInfo, error) {
	request, err := p.sendRequest(ctx, clientId, api_messages.MessageType_ListDir, query)
	if err != nil {
		return nil, err
	}
	results := new(api_messages.ListDirResponse)
	err = proto.Unmarshal(request, results)
	if err != nil {
		zap.L().Warn("failed to unmarshal list dir response", zap.Any("header", request), zap.Error(err))
		return nil, err
	}
	if !results.Status.Success {
		return nil, errorToError(results.Status.Message)
	}
	infos := make([]FileInfo, len(results.Result))
	for i, v := range results.Result {
		infos[i].FileInfo = v
	}
	return infos, nil
}
